<template>
  <!-- 模板内容与原组件一致，无需修改 -->
  <div>
    <template v-if="hasFile" v-for="(file, fileKey) of [innerFile || {}]">
      <a-input
        :key="fileKey"
        :readOnly="true"
        :value="file.name"
      >
        <template slot="addonBefore" style="width: 30px">
          <a-tooltip v-if="file.status === 'uploading'" :title="`上传中(${Math.floor(file.percent)}%)`">
            <a-icon type="loading"/>
          </a-tooltip>
          <a-tooltip v-else-if="file.status === 'done'" title="上传完成">
            <a-icon type="check-circle" style="color:#00DB00;"/>
          </a-tooltip>
          <a-tooltip v-else :title="file.message||'上传失败'">
            <a-icon type="exclamation-circle" style="color:red;"/>
          </a-tooltip>
        </template>
        <span v-if="file.status === 'uploading'" slot="addonAfter">{{ Math.floor(file.percent) }}%</span>
        <template v-else-if="originColumn.allowDownload !== false || originColumn.allowRemove !== false" slot="addonAfter">
          <a-dropdown :trigger="['click']" placement="bottomRight">
            <a-tooltip title="操作">
              <a-icon type="setting" style="cursor: pointer;"/>
            </a-tooltip>
            <a-menu slot="overlay">
              <a-menu-item v-if="originColumn.allowDownload !== false" @click="handleClickDownloadFile">
                <span><a-icon type="download"/>&nbsp;下载</span>
              </a-menu-item>
              <a-menu-item v-if="originColumn.allowRemove !== false" @click="handleClickDeleteFile">
                <span><a-icon type="delete"/>&nbsp;删除</span>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-input>
    </template>
    <a-upload
      v-show="!hasFile"
      name="file"
      :data="{'isup': 1}"
      :multiple="false"
      :action="originColumn.action"
      :headers="uploadHeaders"
      :showUploadList="false"
      v-bind="cellProps"
      @change="handleChangeUpload"
    >
      <a-button icon="upload">{{originColumn.btnText || '点击上传'}}</a-button>
    </a-upload>
  </div>
</template>

<script>
import JVxeCellMixins from '@/components/jeecg/JVxeTable/mixins/JVxeCellMixins'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl } from '@api/manage'

export default {
  name: 'JVxeCustomUploadCell', // 新组件名，与原组件区分
  mixins: [JVxeCellMixins],
  props: {},
  data() {
    return {
      innerFile: null,
    }
  },
  computed: {
    uploadHeaders() {
      let {originColumn: col} = this
      let headers = {}
      if (col.token === true) {
        headers['X-Access-Token'] = this.$ls.get(ACCESS_TOKEN)
      }
      return headers
    },
    hasFile() {
        console.log('上传组件hasFile:', this.innerFile !== null); // 调试用
      return this.innerFile != null
    },
  },
  watch: {
    innerValue: {
      immediate: true,
      handler() {
        if (this.innerValue) {
          this.innerFile = this.innerValue
        } else {
          this.innerFile = null
        }
      },
    },
  },
  methods: {
    // 核心修改：上传后同步attachName和attachUrl到表格行
    handleChangeUpload(info) {
      let { row, originColumn: col } = this; // row是当前表格行数据
      let { file } = info;
      let value = {
        name: file.name,
        type: file.type,
        size: file.size,
        status: file.status,
        percent: file.percent
      }
      if (col.responseName && file.response) {
        value['responseName'] = file.response[col.responseName]
      }
      if (file.status === 'done') {
        if (typeof file.response.success === 'boolean') {
          if (file.response.success) {
            value['path'] = file.response[col.responseName];
            // 关键：同步到当前行的attachName和attachUrl
            row.attachName = file.name; // 文件名
            row.attachUrl = value.path; // 附件地址
          } else {
            value['status'] = 'error';
            value['message'] = file.response.message || '未知错误';
          }
        } else {
          value['path'] = file.response[col.responseName];
          // 同步到当前行的attachName和attachUrl
          row.attachName = file.name;
          row.attachUrl = value.path;
        }
      } else if (file.status === 'error') {
        value['message'] = file.response.message || '未知错误';
      }
      this.innerFile = value;
      // 触发值变更，此时value包含name和path
      if (value.path) {
        this.handleChangeCommon(fileGetValue(value));
      }
    },
    handleClickDownloadFile() {
      let { path } = this.value || {};
      if (path) {
        let url = getFileAccessHttpUrl(path);
        window.open(url);
      }
    },
    // 核心修改：删除时清空行的attachName和attachUrl
    handleClickDeleteFile() {
      const { row } = this;
      row.attachName = ''; // 清空文件名
      row.attachUrl = ''; // 清空附件地址
      this.handleChangeCommon(null);
    },
  },
  // 增强配置：修改value的处理逻辑
  enhanced: {
    switches: { visible: true ,editRender: true },
    getValue: value => fileGetValue(value), // 自定义value转换
    setValue: value => fileSetValue(value),
  }
}

// 核心修改：返回{ attachName, attachUrl }结构
function fileGetValue(value) {
  if (value && value.path) {
    return {
      attachName: value.name, // 文件名
      attachUrl: value.path   // 附件地址
    };
  }
  return value;
}

// 核心修改：从{ attachName, attachUrl }恢复显示
function fileSetValue(value) {
  if (value && value.attachUrl) {
    return {
      name: value.attachName, // 显示文件名
      path: value.attachUrl,  // 关联附件地址
      status: 'done'
    };
  }
  return value;
}
</script>

<style scoped>
/* 样式与原组件一致 */
</style>